#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int e[N], ne[N], w[N], h[N];
int index;
int dis[N];
int flag[N];
int n, m;
void add(int a, int b, int c)
{
	w[index] = c;
	e[index] = b;
	ne[index] = h[a];
	h[a] = index++;
}
int Dij(int x)
{
	memset(dis, 0x3f, sizeof(dis));
	dis[x] = 0;
	priority_queue<PII, vector<PII>, greater<PII>>heap;
	heap.push({ 0,x });
	while (heap.size()) {
		auto temp = heap.top();
		heap.pop();
		int vertex = temp.second;
		int distance = temp.first;
		if (flag[vertex]==1) {
			continue;
		}
		else {
			flag[vertex] = 1;
		}
		for (int i = h[vertex]; i != -1; i = ne[i]) {
			int j = e[i];
			if (dis[j] > distance + w[i]) {
				dis[j] = distance + w[i];
				heap.push({ dis[j],j });
			}
		}
	}
	if (dis[n] == 0x3f3f3f3f) {
		return -1;
	}
	else {
		return dis[n];
	}
}
int main()
{
	memset(h, -1, sizeof(h));
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}
	cout << Dij(1) << endl;
	return 0;
}